//
//  MainV2ViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/9/27.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MainV2ViewController.h"

#import "LZCityPickerController.h"
#import "SDCycleScrollView.h"
#import "AddrChooserViewController.h"

#import "UIScrollView+MHRefresh.h"

#import "HCPhotosWallView.h"
#import "EPMainTabsView.h"
#import "MainSubMainView.h"
#import "MainSubNewsView.h"
#import "MainSubLibraryView.h"
#import "MainSubPublicityView.h"
#import "MainSubLiteratureView.h"

#import "ZCFGV2ViewController.h"
#import "LiteratureViewController.h"
#import "MechanismNewInListViewController.h"
#import "TotalSearchViewController.h"

@interface MainV2ViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) MainV2ViewModel* viewModel;

// UI
@property (weak, nonatomic) UILabel *addressLabel;
@property (weak, nonatomic) UIButton *addressButton;
@property (weak, nonatomic) UILabel *searchLabel;
@property (weak, nonatomic) UIButton *searchButton;

//IBOutlet
@property (weak, nonatomic) IBOutlet UIScrollView* tabContentScrollView;
@property (weak, nonatomic) IBOutlet UIView* mainView;
@property (weak, nonatomic) IBOutlet UIView* tabsView;
@property (weak, nonatomic) IBOutlet UIView* bannerView;

@end

@implementation MainV2ViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
    // ------ 顶部导航栏
    self.navigationItem.titleView = [[UIView alloc] init];
    
    UIView* leftView = [[UIView alloc] init];
    
    UIImage* titleImg = MHImageNamed(@"icon_mainlogo");
    titleImg = [titleImg yy_imageByResizeToSize:(CGSize){(24/titleImg.size.height)*titleImg.size.width, 24}];
    UIImageView* titleImgView = [[UIImageView alloc] initWithImage:titleImg];
    titleImgView.frame = (CGRect) {4, 10, titleImg.size};
    [leftView addSubview:titleImgView];
    
    UIView* searchView = [[UIView alloc] initWithFrame:(CGRect) {CGRectGetMaxX(titleImgView.frame) + 8, 8, 88, 28}];
    searchView.backgroundColor = UIColorHex(#f0f0f0);
    searchView.layer.cornerRadius = 5.0f;
    searchView.layer.masksToBounds = YES;
    UILabel* searchLabel = [[UILabel alloc] initWithFrame:(CGRect) {4 + 28, 0, 88-28-8, 28}];
    searchLabel.text = [DataManager sharedDataManager].totalStationSearchKey;
    searchLabel.font = [UIFont systemFontOfSize:12.0f];
    searchLabel.textColor = UIColorHex(#999999);
    [searchView addSubview:searchLabel];
    self.searchLabel = searchLabel;
    UIButton* searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = (CGRect) {4, 0, 28, 28};
    [searchBtn setImage:[UIImage imageNamed:@"icon_graySearch"] forState:UIControlStateNormal];
    searchBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [searchView addSubview:searchBtn];
    UIButton* bsearchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    bsearchBtn.frame = (CGRect) {0, 0, searchView.frame.size};
    bsearchBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [searchView addSubview:bsearchBtn];
    
    self.searchButton = bsearchBtn;
    [leftView addSubview:searchView];
    
    leftView.frame = (CGRect) {0, 0, 88+titleImg.size.width, 44};
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIView* cityView = [[UIView alloc] initWithFrame:(CGRect) {0, 0, 0, 64}];
    
    UILabel* cityLabel = [[UILabel alloc] initWithFrame:(CGRect) {0, 0, 0, 44}];
    cityLabel.text = @"汕头市 >";
    cityLabel.textColor = Color_MainGreen;
    cityLabel.font = [UIFont systemFontOfSize:14.0f];
    cityLabel.textAlignment = NSTextAlignmentRight;
    [cityView addSubview:cityLabel];
    
    UIImageView* cityArrowImg = [[UIImageView alloc] initWithFrame:(CGRect) {0, 12, 22, 27}];
    cityArrowImg.image = [UIImage imageNamed:@"icon_location"];
    cityArrowImg.contentMode = UIViewContentModeCenter;
    [cityView addSubview:cityArrowImg];
    
    UIButton* cityBtn = [[UIButton alloc] initWithFrame:(CGRect) {0, 0, 0, 44}];
    [[cityBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _push2AddrPop];
    }];
    [cityView addSubview:cityBtn];
    
    [cityLabel mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.height.mas_equalTo(44);
         
         make.left.mas_equalTo(cityArrowImg.mas_right);
         make.top.mas_equalTo(0);
         make.bottom.mas_equalTo(0);
         make.right.mas_equalTo(0);
     }];
    
    [cityArrowImg mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.height.mas_equalTo(22);
         make.width.mas_equalTo(27);
         
         make.left.mas_equalTo(0);
         make.right.mas_equalTo(cityLabel.mas_left).mas_offset(0);
         make.top.mas_equalTo(0);
         make.bottom.mas_equalTo(0);
     }];
    
    [cityBtn mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.left.mas_equalTo(0);
         make.right.mas_equalTo(0);
         make.top.mas_equalTo(0);
         make.bottom.mas_equalTo(0);
     }];
    
    [cityView mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.height.mas_equalTo(64);
     }];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:cityView];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.addressLabel = cityLabel;
    self.addressButton = cityBtn;
    
    // ------ 内容
    
    // ------ 底部Tabbar
    self.tabBarItem.title = @"首页";
    self.tabBarItem.image = [[UIImage imageNamed:@"tabbar_home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tabbar_home_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
//    self.view.backgroundColor = [UIColor redColor];
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    DataManager* dm = [DataManager sharedDataManager];
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self);
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:didAppearSignal] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    [[[willAppearSignal replay] take:1] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self.viewModel.reqLoadingImgCmd execute:nil];
    }];
    
    [[self.searchButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _push2SearchVC];
    }];
    
    RACSignal* addressChangeSignal = [RACObserve(self.viewModel, zone) distinctUntilChanged];
    RAC(self.addressLabel, text) = [[addressChangeSignal replay] map:^id(id value)
    {
        NSString* strResult = value;
        
        strResult = HCStrFormat(@"%@ >", strResult);
        
        return strResult;
    }];
}

#pragma mark - 更新初始化 操作
- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    [self _setupTabsView];
    
    [self _setupContentScrollView];
}

- (void)_setupTabsView
{
    @weakify(self);
    
    CGSize tabContentScrollViewSize = self.tabContentScrollView.frame.size;
    
    EPMainTabsViewModel* vm = [[EPMainTabsViewModel alloc] init];
    vm.tabInfos = @[@{@"TabName":@"生态云"}, @{@"TabName":@"环保要闻"}, @{@"TabName":@"环保文库"}, @{@"TabName":@"环保公示"}, @{@"TabName":@"生态文献"}];
    [vm.didClickTab subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSLog(@"TabsView select index : %d", [x integerValue]);
         
         NSInteger index = [x integerValue];
         
         if (3 == index)
         {
             UIView* tabContentView = [self.tabContentScrollView viewWithTag:100];
             MainSubPublicityView* view = [tabContentView viewWithTag:4];
             [view reloadAllView];
         }
         
         [self.tabContentScrollView scrollRectToVisible:(CGRect) {index*tabContentScrollViewSize.width, 0, tabContentScrollViewSize} animated:YES];
     }];
    
    EPMainTabsView* curView = [[EPMainTabsView alloc] initWithFrame:(CGRect) {0, 0, self.tabsView.frame.size}];
    [curView bindViewModel:vm];
    curView.tag = 99;
    [self.tabsView addSubview:curView];
}

- (void)_setupContentScrollView
{
    @weakify(self);
    
    CGFloat scrollViewWidth = [UIScreen mainScreen].bounds.size.width * 5;
    NSLog(@"scrollViewWidth 1 : %f", scrollViewWidth);
    
    UIView* tabContentView = [self.tabContentScrollView viewWithTag:100];
    
    tabContentView.backgroundColor = [UIColor yellowColor];
    
//    NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"MainSubMainView" owner:nil options:nil];
//    UIView* mainView = [views lastObject];
//    mainView.frame = (CGRect) {0, 0, self.view.frame.size};
//    [tabContentView addSubview:mainView];
    
    
    for (NSLayoutConstraint* curConstraint in tabContentView.constraints)
    {
        if (curConstraint.firstAttribute == NSLayoutAttributeWidth)
        {
            curConstraint.constant = scrollViewWidth;
            break;
        }
    }
    [tabContentView setNeedsUpdateConstraints];
    [tabContentView updateConstraintsIfNeeded];
    [tabContentView setNeedsLayout];
    [tabContentView layoutIfNeeded];
    
    // 首页
    MainSubViewModel* mainSubVM = [[MainSubViewModel alloc] initWithParams:@{}];
    [[mainSubVM.jglbCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _push2MechanismListVC];
    }];
    NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"MainSubMainView" owner:nil options:nil];
    MainSubMainView* mainView = [views lastObject];
    mainView.frame = (CGRect) {0, 0, self.tabContentScrollView.bounds.size};
    [mainView bindViewModel:mainSubVM];
    mainView.tag = 1;
    [tabContentView addSubview:mainView];
    
    // 环保要闻
    MainSubNewsViewModel* mainSubNewsVM = [[MainSubNewsViewModel alloc] initWithParams:@{}];
    views = [[NSBundle mainBundle] loadNibNamed:@"MainSubNewsView" owner:nil options:nil];
    MainSubNewsView* mainNewsView = [views lastObject];
    mainNewsView.frame = (CGRect) {self.tabContentScrollView.bounds.size.width, 0, self.tabContentScrollView.bounds.size};
    [mainNewsView bindViewModel:mainSubNewsVM];
    mainNewsView.tag = 2;
    [tabContentView addSubview:mainNewsView];
    
    // 环保文库
    MainSubLibraryViewModel* mainSubLibraryVM = [[MainSubLibraryViewModel alloc] initWithParams:@{}];
    [[mainSubLibraryVM.chooseCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self);
        
        [self _push2LibraryByID:x];
    }];
//    [[mainSubLibraryVM.zcfgBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//       @strongify(self);
//
//        [self _push2LibraryByName:@"政策法规"];
//    }];
//    [[mainSubLibraryVM.hbbzBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//        @strongify(self);
//
//        [self _push2LibraryByName:@"环保标准"];
//    }];
//    [[mainSubLibraryVM.hjjcBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//        @strongify(self);
//
//        [self _push2LibraryByName:@"环境监察"];
//    }];
//    [[mainSubLibraryVM.hpbgBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//        @strongify(self);
//
//        [self _push2LibraryByName:@"环评报告"];
//    }];
//    [[mainSubLibraryVM.qjscBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//        @strongify(self);
//
//        [self _push2LibraryByName:@"清洁生产"];
//    }];
//    [[mainSubLibraryVM.zlfaBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//        @strongify(self);
//
//        [self _push2LibraryByName:@"治理方案"];
//    }];
//    [[mainSubLibraryVM.yjyaBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//        @strongify(self);
//
//        [self _push2LibraryByName:@"应急预案"];
//    }];
//    [[mainSubLibraryVM.qtBtnCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
//        @strongify(self);
//
//        [self _push2LibraryByName:@"相关文件"];
//    }];
    views = [[NSBundle mainBundle] loadNibNamed:@"MainSubLibraryView" owner:nil options:nil];
    MainSubLibraryView* mainLibraryView = [views lastObject];
    mainLibraryView.frame = (CGRect) {self.tabContentScrollView.bounds.size.width*2, 0, self.tabContentScrollView.bounds.size};
    [mainLibraryView bindViewModel:mainSubLibraryVM];
    mainLibraryView.tag = 3;
    [tabContentView addSubview:mainLibraryView];
    
    // 环保公示
    MainSubPublicityViewModel* mainSubPublicityVM = [[MainSubPublicityViewModel alloc] initWithParams:@{}];
    views = [[NSBundle mainBundle] loadNibNamed:@"MainSubPublicityView" owner:nil options:nil];
    MainSubPublicityView* mainPublicityView = [views lastObject];
    mainPublicityView.frame = (CGRect) {self.tabContentScrollView.bounds.size.width*3, 0, self.tabContentScrollView.bounds.size};
    [mainPublicityView bindViewModel:mainSubPublicityVM];
    mainPublicityView.tag = 4;
    [tabContentView addSubview:mainPublicityView];
    
    // 生态文献
    MainSubLiteratureViewModel* mainSubLiteratureVM = [[MainSubLiteratureViewModel alloc] initWithParams:@{}];
    views = [[NSBundle mainBundle] loadNibNamed:@"MainSubLiteratureView" owner:nil options:nil];
    MainSubLiteratureView* mainLiteratureView = [views lastObject];
    mainLiteratureView.frame = (CGRect) {self.tabContentScrollView.bounds.size.width*4, 0, self.tabContentScrollView.bounds.size};
    [mainLiteratureView bindViewModel:mainSubLiteratureVM];
    mainLiteratureView.tag = 5;
    [tabContentView addSubview:mainLiteratureView];
}

#pragma mark - Delegate 一些无法用RAC实现
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_push2AddrPop
{
    DataManager* dm = [DataManager sharedDataManager];
    
    @weakify(self)
    AddrChooserViewModel* vm = [[AddrChooserViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"选择地区"}];
    vm.chooseBlock = ^(ProvinceListData* choosePData)
    {
        @strongify(self);
        
        [self.viewModel resetZoneData:choosePData];
        
//        NSString* province = @"";
//        NSString* city = @"";
//        NSString* zone = @"";
//
//        if ([choosePData.parentID isNotBlank])
//        {
//            for (ProvinceListData* provinceData in dm.addrData.datas)
//            {
//                if ([provinceData.areaID isEqualToString:choosePData.parentID])
//                {
//                    province = provinceData.name;
//
//                    break;
//                }
//            }
//
//            city = choosePData.name;
//        }
//        else
//        {
//            province = choosePData.name;
//        }
//
//        dm.address = HCStrFormat(@"%@-%@-%@", province, city, zone);
        
//        self.viewModel.chooseProvinceData = choosePData;
    };
    AddrChooserViewController* vc = [[AddrChooserViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2LibraryByID:(NSString*)cateID
{
    DataManager* dm = [DataManager sharedDataManager];
    LiteratureViewModel* lvm = [[LiteratureViewModel alloc] initWithParams:@{}];
    lvm.cateID = cateID;
    [lvm resetZoneData:self.viewModel.zoneData];
    LiteratureViewController* lvc = [[LiteratureViewController alloc] initWithViewModel:lvm];
    [self.navigationController pushViewController:lvc animated:YES];
    
//    ZCFGV2ViewModel* vm = [[ZCFGV2ViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"政策法规"}];
//    ZCFGV2ViewController* vc = [[ZCFGV2ViewController alloc] initWithViewModel:vm];
//    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2MechanismListVC
{
    MechanismNewInListViewModel* vm = [[MechanismNewInListViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"环保机构"}];
    MechanismNewInListViewController* vc = [[MechanismNewInListViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2SearchVC
{
    TotalSearchViewModel* vm = [[TotalSearchViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"搜索"}];
    TotalSearchViewController* vc = [[TotalSearchViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

@end

